<template>
  <z-dialog
    :visible.sync="visible"
    :title="title"
    width="30%"
    :disabled="disabled"
    @cancel="handelCancel"
    @ok="handelOk"
  >
    <el-form
      ref="form"
      :model="form"
      label-width="80px"
      :rules="rules"
      :disabled="disabled"
    >
      <el-form-item label="始发港" prop="departurePort">
        <el-input v-model="form.departurePort"></el-input>
      </el-form-item>
      <el-form-item label="目的港" prop="destinationPort">
        <el-input v-model="form.destinationPort"></el-input>
      </el-form-item>
    </el-form>
  </z-dialog>
</template>

<script>
import {
  getHomeData as addApi,
  queryPage as getDetailApi,
} from "@/api/test/test";
import { getLoginUser as editApi } from "@/api/login/login";

export default {
  data() {
    return {
      visible: false,
      title: "",
      disabled: false,
      // form的所有字段要写全
      form: {
        id: "",
        departurePort: "",
        destinationPort: "",
      },
      rules: {
        departurePort: [
          { required: true, message: "请输入始发港", trigger: "blur" },
        ],
        destinationPort: [
          { required: true, message: "请输入目的港", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    show(type, id) {
      this.form.id = id;
      switch (type) {
        case "add":
          this.disabled = false;
          this.title = "新增";
          break;
        case "edit":
          this.disabled = false;
          this.title = "编辑";
          this.getDetail();
          break;
        case "view":
          this.disabled = true;
          this.title = "详情";
          this.getDetail();
          break;
      }
      this.visible = true;
    },
    getDetail() {
      getDetailApi({ id: this.form.id }).then((res) => {
        this.setData(res.records[0]);
      });
    },
    setData(obj) {
      const form = this._.cloneDeep(this.form);
      for (const i in form) {
        if (obj[i] !== undefined) {
          form[i] = obj[i];
        }
      }
      this.form = form;
    },
    handelCancel(done) {
      // this.form = this.$options.data().form;
      this.$refs.form.resetFields();
      done();
    },
    handelOk(done) {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const requestApi = this.form.id ? editApi : addApi;
          const message = this.form.id ? "修改成功！" : "提交成功！";
          requestApi(this._.cloneDeep(this.form)).then(() => {
            done(message);
          });
        }
      });
    },
  },
};
</script>

<style scoped lang="less"></style>
